package com.jeffgalper.feather;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;

public abstract class AbstractFeathered implements Feathered {

  protected FileChannel mFC;

  public AbstractFeathered(FileChannel fc) {
    mFC = fc;
  }

  protected String readFilename(short filenameSize) throws IOException {
    ByteBuffer bb = ByteBuffer.allocate(filenameSize);
    mFC.read(bb);
    return new String(bb.array(), "UTF-16LE");
  }

  protected short readFilenameSize() throws IOException {
    ByteBuffer bb = ByteBuffer.allocate(Short.SIZE / Feather.BITS_PER_BYTE);
    mFC.read(bb);
    bb.rewind();
    return bb.getShort();
  }

  protected void skipHeader() throws IOException {
    int headerSize = Feather.MAGIC_FEATHER_BB.capacity()
        + Feather.VERSION_BB.capacity();
    mFC.position(mFC.position() + headerSize);
  }

  protected long readSize() throws IOException {
    ByteBuffer bb = ByteBuffer.allocate(Long.SIZE / Feather.BITS_PER_BYTE);
    System.out.println("reading size");
    mFC.read(bb);
    System.out.println("read size");
    System.out.println(Arrays.toString(bb.array()));
    bb.rewind();
    return bb.getLong();
  }
}
